//
//  OCJNetWorkCenter.m
//  OCJ
//
//  Created by yangyang on 2017/4/21.
//  Copyright © 2017年 OCJ. All rights reserved.
//

#import "OCJNetWorkCenter.h"
//#import "OCJProgressHUD.h"
#import "AFNetworking.h"

static NSString* ocjBaseUrl = @"http://47.96.36.253"; ///< 服务器根域名地址
//static NSString* ocjBaseUrl = @"http://10.22.2.78:9091"; ///< 侯域名地址


static NSInteger ocjHttpRequestTimeoutInterval = 600; ///< 请求超时时间

@implementation OCJNetWorkCenter
#pragma mark - 接口方法实现区域
+ (instancetype)sharedCenter{
    static dispatch_once_t onceTaken;
    static OCJNetWorkCenter * sharedCenter;
    dispatch_once(&onceTaken, ^{
        sharedCenter = [[OCJNetWorkCenter alloc]init];
        
    });
    return sharedCenter;
}

+(void)ocj_monitorNetworkStatus{
    [[AFNetworkReachabilityManager sharedManager]startMonitoring];//启动检测网络状态
    OCJNetWorkCenter * sharedCenter = [self sharedCenter];
    [MY_NOTICE_CENTER addObserver:sharedCenter selector:@selector(ocj_MonitoringNetWorkStautes:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
}

-(void)ocj_POSTWithUrlPath:(NSString *)urlPath parameters:(NSDictionary *)parameters andLodingType:(OCJHttpLoadingType)loadingType completionHandler:(OCJHttpResponseHander)handler{
    NSString * accessToken = [[NSUserDefaults standardUserDefaults]objectForKey:OCJAccessToken];
    if (![urlPath isEqualToString:@"/oauth/app/token"] || ![urlPath isEqualToString:@"/oauth/sms"]) {
 
    }
    else
    {
        if (![accessToken stringIsValid]) {
            [MY_NOTICE_CENTER postNotificationName:NEED_LOGIN object:nil];
            return;
        }
    }

    switch (loadingType) {
        case OCJHttpLoadingTypeBegin:
//            hud = [OCJProgressHUD ocj_showHudWithView:topVC.view andHideDelay:2];
            break;
            
        case OCJHttpLoadingTypeBeginAndEnd:
//            hud = [OCJProgressHUD ocj_showHudWithView:topVC.view andHideDelay:0];
            break;
        default:
            break;
    }
    
    if (loadingType != OCJHttpLoadingTypeNone) {
        if (![self ocj_checkNetworkIsNormal]) {
//            [WSHHAlert wshh_showHudWithTitle:@"网络情况异常，请检查设备网络" andHideDelay:2];
//            [hud ocj_hideHud];
            return;
        }
    }
    
    
    //请求处理
    if (parameters == nil) {
        parameters = @{};
    }
    NSData* postBody = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc]initWithData:postBody encoding:NSUTF8StringEncoding];
    NSLogEX(@"发送请求%@：%@",urlPath,str);
    
    AFURLSessionManager* manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", ocjBaseUrl, urlPath];
    requestUrl = [self ocj_POST_joinCommonParameterWithUrl:requestUrl];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST"
                                                                                 URLString:requestUrl
                                                                                parameters:nil
                                                                                     error:nil];
    request.timeoutInterval = ocjHttpRequestTimeoutInterval;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    NSString * accessToken = [[NSUserDefaults standardUserDefaults]objectForKey:OCJAccessToken];
    if (accessToken.length>0) {
        [request setValue:accessToken forHTTPHeaderField:@"Authorization"];
    }
    [request setHTTPBody:postBody];
    
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript",@"text/plain",nil];
    manager.responseSerializer = responseSerializer;
    
    __weak OCJNetWorkCenter* weakSelf = self;
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (error) {
            [weakSelf ocj_dealWithFailureResponseWithError:error completionHandler:handler];
        }else{
            [weakSelf ocj_dealWithSuccessResponse:responseObject urlPath:urlPath completionHandler:handler];
        }
        
//        if (hud) {
//            [hud ocj_hideHud];
//        }
    }] resume];
    
}

-(void)ocj_fromData_POSTWithUrlPath:(NSString *)urlPath prameters:(NSDictionary*)parmeters files:(NSArray<NSDictionary*> *)files andLodingType:(OCJHttpLoadingType)loadingType completionHandler:(OCJHttpResponseHander)handler{
    NSString * accessToken = [[NSUserDefaults standardUserDefaults]objectForKey:OCJAccessToken];
    if (![accessToken stringIsValid]) {
        [MY_NOTICE_CENTER postNotificationName:NEED_LOGIN object:nil];
        return;
    }
    switch (loadingType) {
        case OCJHttpLoadingTypeBegin:
//            hud = [OCJProgressHUD ocj_showHudWithView:topVC.view andHideDelay:2];
            break;
            
        case OCJHttpLoadingTypeBeginAndEnd:
//            hud = [OCJProgressHUD ocj_showHudWithView:topVC.view andHideDelay:0];
            break;
        default:
            break;
    }
    
    if (![self ocj_checkNetworkIsNormal]) {
//        [WSHHAlert wshh_showHudWithTitle:@"网络情况异常，请检查设备网络" andHideDelay:2];
//        [hud ocj_hideHud];
        return;
    }
    
    //请求处理
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", ocjBaseUrl, urlPath];
    requestUrl = [self ocj_POST_joinCommonParameterWithUrl:requestUrl];
    
    __weak OCJNetWorkCenter* weakSelf = self;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    NSString * accessToken = [[NSUserDefaults standardUserDefaults]objectForKey:OCJAccessToken];
    if (accessToken.length>0) {
        [manager.requestSerializer setValue:accessToken forHTTPHeaderField:@"Authorization"];
    }
    [manager POST:requestUrl parameters:parmeters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLogEX (@"JSON: %@", responseObject);
        //Data解析
        [weakSelf ocj_dealWithSuccessResponse:responseObject urlPath:urlPath completionHandler:handler];
       
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf ocj_dealWithFailureResponseWithError:error completionHandler:handler];
    }];
    
}



-(void)ocj_GETWithUrlPath:(NSString *)urlPath parameters:(NSDictionary *)parameters andLodingType:(OCJHttpLoadingType)loadingType completionHandler:(OCJHttpResponseHander)handler{
    NSString * accessToken = [[NSUserDefaults standardUserDefaults]objectForKey:OCJAccessToken];
    if (![accessToken stringIsValid]) {
        [MY_NOTICE_CENTER postNotificationName:NEED_LOGIN object:nil];
        return;
    }
    
    switch (loadingType) {
        case OCJHttpLoadingTypeBegin:
//            hud = [OCJProgressHUD ocj_showHudWithView:topVC.view andHideDelay:2];
            break;
        case OCJHttpLoadingTypeBeginAndEnd:
//            hud = [OCJProgressHUD ocj_showHudWithView:topVC.view andHideDelay:0];
            break;
        default:
            break;
    }
    
//    if (![self ocj_checkNetworkIsNormal]) {
////        [WSHHAlert wshh_showHudWithTitle:@"网络情况异常，请检查设备网络" andHideDelay:2];
////        [hud ocj_hideHud];
//        return;
//    }
    
//    parameters = [self ocj_GET_joinCommonParameterWithParameters:parameters];
    
    NSLogEX(@"发送请求%@：%@",urlPath,parameters);
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", ocjBaseUrl, urlPath];
    __weak OCJNetWorkCenter* weakSelf = self;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    if (accessToken.length>0) {
        [manager.requestSerializer setValue:accessToken forHTTPHeaderField:@"Authorization"];
    }
    [manager GET:requestUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLogEX (@"JSON: %@", responseObject);
        [weakSelf ocj_dealWithSuccessResponse:responseObject urlPath:urlPath completionHandler:handler];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf ocj_dealWithFailureResponseWithError:error completionHandler:handler];
    }];
    
}


#pragma mark - 私有方法实现区域
/**
 GET请求设置http-head
 */
-(AFHTTPSessionManager*)ocj_setHttp{
    
    //Http 相关设置
    AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:ocjBaseUrl]];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = ocjHttpRequestTimeoutInterval;
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript",@"text/plain",nil];
    manager.responseSerializer = responseSerializer;
    
    return manager;
}


/**
 POST 加通用参数
 */
-(NSString*)ocj_POST_joinCommonParameterWithUrl:(NSString*)urlStr{
    NSString*  urlLastStr = urlStr;
    
    NSString * accessToken = [[NSUserDefaults standardUserDefaults]objectForKey:OCJAccessToken];
    if (accessToken.length>0) {
        urlLastStr = [NSString stringWithFormat:@"%@?access_token=%@",urlLastStr,accessToken];
    }
    
//    [[NSUserDefaults standardUserDefaults]setObject:@"123" forKey:OCJDeviceID];
//    NSString* deviceID = [[NSUserDefaults standardUserDefaults]objectForKey:OCJDeviceID];//登录凭证
//    if (deviceID.length>0) {
//        if ([urlLastStr containsString:@"?"]) {
//            urlLastStr = [NSString stringWithFormat:@"%@&device_id=%@",urlLastStr,deviceID];
//        }else{
//            urlLastStr = [NSString stringWithFormat:@"%@?device_id=%@",urlLastStr,deviceID];
//        }
//    }
    
    return urlLastStr;
}

/**
 GET 加通用参数
 */
-(NSDictionary*)ocj_GET_joinCommonParameterWithParameters:(NSDictionary*)parameters{
    NSMutableDictionary* mDic;
    if (parameters) {
       mDic = [parameters mutableCopy];
    }else{
        mDic = [NSMutableDictionary dictionary];
    }
    
    NSString * accessToken = [[NSUserDefaults standardUserDefaults]objectForKey:OCJAccessToken];
    if (accessToken.length>0) {
        [mDic setObject:accessToken forKey:OCJAccessToken];
    }
    
//    [[NSUserDefaults standardUserDefaults]setObject:@"123" forKey:OCJDeviceID];
//    NSString* deviceID = [[NSUserDefaults standardUserDefaults]objectForKey:OCJDeviceID];//登录凭证
//    if (deviceID.length>0) {
//        [mDic setObject:deviceID forKey:OCJDeviceID];
//    }
    
    return [mDic copy];
}



/**
 监测网络状态变化

 @param notice 通知
 */
-(void)ocj_MonitoringNetWorkStautes:(NSNotification*)notice{
    
    NSLogEX(@"网络状态改变：%@",notice.userInfo);
    NSInteger status = [notice.userInfo[@"AFNetworkingReachabilityNotificationStatusItem"] integerValue];
    switch (status) {
        case 0:
//            [WSHHAlert wshh_showHudWithTitle:@"网络连接中断，请检查设备网络" andHideDelay:2];
            break;
        case 1:
//            [WSHHAlert wshh_showHudWithTitle:@"设备网络变为运营商网络，请注意" andHideDelay:2];
            break;
        case 2:
//            [WSHHAlert wshh_showHudWithTitle:@"设备网络变为WI-FI网络，请注意" andHideDelay:2];
            break;
            
        default:
            break;
    }
}


/**
 检测网络可用性
 */
-(BOOL)ocj_checkNetworkIsNormal{
    BOOL isRechable = [AFNetworkReachabilityManager sharedManager].isReachable;
    return isRechable;
}


/**
 处理http成功响应
 */
- (void)ocj_dealWithSuccessResponse:(id)responseObject urlPath:(NSString*)urlPath completionHandler:(OCJHttpResponseHander)handler{
    
    OCJBaseResponceModel* responceModel = [[OCJBaseResponceModel alloc]init];
    
    if ([responseObject isKindOfClass:[NSDictionary class]]) {
        
        [responceModel setValuesForKeysWithDictionary:responseObject];
        handler(responceModel);
        
        //调试日志=========
        NSData* data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLogEX(@"接口返回%@:%@",urlPath,str);
        
    }else if([responseObject isKindOfClass:[NSData class]]){
        NSDictionary* resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (!resultDic) {//服务器返回格式非json
            NSString* str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLogEX(@"接口返回%@:%@",urlPath,str);
            
            responceModel.ocjStr_code = @"-1";
            responceModel.ocjStr_message = @"服务器返回数据非json";
            handler(responceModel);
            return ;
        }
        
        [responceModel setValuesForKeysWithDictionary:resultDic];
        handler(responceModel);
        
        //调试日志=========
        if ([resultDic isKindOfClass:[NSDictionary class]]) {
            NSData* data = [NSJSONSerialization dataWithJSONObject:resultDic options:NSJSONWritingPrettyPrinted error:nil];
            NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLogEX(@"接口返回%@:%@",urlPath,str);
        }else{
            NSLogEX(@"接口返回%@:%@",urlPath,resultDic);
        }
        
        
    }else{
        
        responceModel.ocjStr_code = @"-1";
        responceModel.ocjStr_message = @"服务器出问题了";
        handler(responceModel);
    }
    
    [self ocj_dealWithAccessTokenLoseEfficacyWithResponceModel:responceModel];//过一遍accessToken的筛子
}


/**
 发送token失效的通知
 */
- (void)ocj_dealWithAccessTokenLoseEfficacyWithResponceModel:(OCJBaseResponceModel*)model{
    
    if ([model.ocjStr_code isEqualToString:@"300006"] || [model.ocjStr_code isEqualToString:@"4012"] || [model.ocjStr_code isEqualToString:@"4013"] || [model.ocjStr_code isEqualToString:@"4014"] || [model.ocjStr_code isEqualToString:@"4010"]) {
        
        [MY_NOTICE_CENTER postNotificationName:NEED_LOGIN object:nil];
    }
}


/**
 处理http失败响应
 */
- (void)ocj_dealWithFailureResponseWithError:(NSError*)error completionHandler:(OCJHttpResponseHander)handler{
    
    OCJBaseResponceModel* responceModel = [[OCJBaseResponceModel alloc]init];
    responceModel.ocjStr_code = @"-2";
    responceModel.ocjStr_message = @"设备网络出问题了";
    handler(responceModel);
    
    NSLogEX(@"接口错误：%@",error.description);
//    [WSHHAlert wshh_showHudWithTitle:error.localizedDescription andHideDelay:2];
    
}

@end
